/********************************************************************************
 * Copyright (c)2016-2020, ShenZhen WanJiaAn Technology CO.,LTD.
 * All Rights Reserved.
 *
 * File Name     : hi3861l.c
 * Author        : joki.zhu
 * Date          : 2020-07-06
 *
 * Record        :
 * 1.Date        : 2020-07-06
 *   Author      : joki.zhu
 *   Modification: Created file
 ********************************************************************************/
#include "app_common.h"
#include "DevWifi.h"
#include "DevKey.h"
#include "DevLed.h"
#include "Audio.h"
#include "hi_hal_syslink.h"
#include "DevSocSub.h"

#ifdef YD_PROTOCOL
#include "dot_define.h"
#include "DOTSdkAPI.h"
#endif

typedef struct {
    char bInit;
    char bConnecting;
    pthread_t wifiProcPid;
    WIFI_CONFIG_STATUS_E enConfigStatus;
    WIFI_CONNECTION_STATUS enConnnectStatus;
}hi3861_context_s;

 static hi3861_context_s g_hi386lCtx = {
    .bInit = 0,
    .bConnecting = 0,
    .wifiProcPid = -1,
    .enConfigStatus = WIFI_CONFIG_NONE,
    .enConnnectStatus = WIFI_DISCONNECTED,
 };


 static inline hi3861_context_s *_hi3861_GetCtx(void)
 {
     return &g_hi386lCtx;
 }

 static void _onRecvWifiEvent(HI_SYSLINK_PARM_S stRcvMsg)
 {
     if (HI_SYSLINK_MSGID_W2S_WIFI_EVENT == stRcvMsg.u32MsgId)
     {
        LOGD("data[0]: %d\n", stRcvMsg.data[0]);

        hi3861_context_s *ctx = _hi3861_GetCtx();
        
        if (stRcvMsg.data[0] == 0) {
            ctx->enConnnectStatus = WIFI_DISCONNECTED;
        } else if (stRcvMsg.data[0] == 1) {
            ctx->enConnnectStatus = WIFI_CONNECTED;
        }
     }
 }

 static int _wifi_set_config(char *ssid, char *password, char *encrypt)
 {
#ifdef DEV_CONFIG
     DevConfigSetWifi(ssid, password, encrypt);
#else
     ConfigSetEnv(ENV_WIFI_TOKEN, ENV_WIFI_KEY_SSID, ssid);
     ConfigSetEnv(ENV_WIFI_TOKEN, ENV_WIFI_KEY_PASSWORD, password);
     ConfigSetEnv(ENV_WIFI_TOKEN, ENV_WIFI_ENCRYPT, encrypt);
     ConfigSave();
#endif /* DEV_CONFIg */
     return 0;
 }

 static int _wifi_get_config(char *ssid, char *password, char *encrypt)
 {
#ifdef DEV_CONFIG
     DevConfigGetWifi(ssid, password, encrypt);
     if (ssid != NULL && strlen(ssid) == 0)
     {
         if (ssid != NULL) {
             ConfigGetEnv(ENV_WIFI_TOKEN, ENV_WIFI_KEY_SSID, ssid);        
         }
         if (password != NULL) {
             ConfigGetEnv(ENV_WIFI_TOKEN, ENV_WIFI_KEY_PASSWORD, password);
         }
         if (encrypt != NULL) {
             ConfigGetEnv(ENV_WIFI_TOKEN, ENV_WIFI_ENCRYPT, encrypt);
         }
     }
#else
     if (ssid != NULL) {
         ConfigGetEnv(ENV_WIFI_TOKEN, ENV_WIFI_KEY_SSID, ssid);
     }
     if (password != NULL) {
         ConfigGetEnv(ENV_WIFI_TOKEN, ENV_WIFI_KEY_PASSWORD, password);
     }
     if (encrypt != NULL) {
         ConfigGetEnv(ENV_WIFI_TOKEN, ENV_WIFI_ENCRYPT, encrypt);
     }
#endif /* DEV_CONFIG */
     return 0;
 }

 /* solve chinese ssid */
 static char *_wifi_ssid_conver(char *before, char *bHex)
 {
     unsigned int i;
     char *ch1;
     int flag_hex = 0;              
     static char after[32 * 4 + 1];
     
     memset(after, 0, 32 * 4 + 1);
     if (before == NULL || bHex ==NULL) {
         return after;
     }
 
     /* Whether it is GBK code */
     for (i = 0; i < strlen(before); i++) 
     {
         if (before[i] < 32 || before[i] > 127) {
             flag_hex = 1;
             break;
         }
     }
     ch1 = &after[0];
     if (flag_hex) /* GBK, without '"' */
     {
         *bHex = 1;
         i = 0;
         for (;;) {
             if (before[i] == 0) {
                 break;
             }
             if (before[i] < 32 || before[i] > 127) {
                 sprintf(ch1, "\\x%02x", (unsigned char)before[i]);
                 ch1 += 4;
             } else {
                 sprintf(ch1, "%c", (unsigned char)before[i]);
                 ch1 += 1;
             }
             i++;
         }
     }
     else /* ASCII SSID, need '"' */
     {
         *bHex = 0;
#ifdef __HuaweiLite__
         strcpy(after, before);
#else
         after[0] ='"';
         strcpy(after+1, before);
         after[strlen(before) + 1] = '"';
#endif /* __HuaweiLite__ */
     }
 
     return after;
 }

 void *_MCGetRegisterStatus(void*args)
 {
	DOTRegisterSetLock();
	for (int i = 0; i < 120; i++)
	{//120秒连不上就认定是失败
		LOGW("MCGetRegisterStatus,i=%d\n", i);
		if (MC_get_register_status())
		{
			return;
		}
		sleep(1);
	}
	if (!DOTGetConfigFailParam() && !DOTGetWifiConfigRun())
	{
		while (AudioGetOpsHandle()->play_file_start(AUDIO_CONFIG_FAIL, AUDIO_TYPE_MP3, 0) < 0)
		{
			usleep(100 * 1000);
		}
		DOTSetConfigFailParam(1);		
		sleep(5);
	}
	//DOTStopBind();
	//	WifiSetDefaultConfig();
	//	SystemReboot("yd register failed");
	printf("_MCGetRegisterStatus DOTRegisterSetUnlock start\n");
	DOTRegisterSetUnlock();
	printf("_MCGetRegisterStatus DOTRegisterSetUnlock end\n");
	PowerSetSocSleepTime(AV_TRUE, 5);
	printf("_MCGetRegisterStatus PowerSetSocSleepTime start\n");
 }

void *tskHi3861WifiProc(void*args)
{
    SET_THREAD_NAME("tskHi3861WifiProc");
    pthread_detach(pthread_self());  

    hi3861_context_s *ctx = _hi3861_GetCtx();
    char ssid[32] = "";
    char pwd[64] = "";
    int connect_count_num = 0; 
#ifdef YD_PROTOCOL
    char mac[32] = { 0 };
    char mac_bak[32] = { 0 };
#endif
    _wifi_get_config(ssid, pwd, NULL);

#if 1
    SYSTEM_WAKEUP_TYPE_E enSysWakeupType = SYS_WAKEUP_TYPE_BUFF;

    SocSubGetWakeUpType(&enSysWakeupType);
    if (SYS_WAKEUP_TYPE_KEY_NETCFG != enSysWakeupType) {
        WIFI_STATUS_INFO_S stStatusInfo;
        memset(&stStatusInfo, 0, sizeof(stStatusInfo));
        hi3861L_get_status(&stStatusInfo);
#ifndef YD_PROTOCOL
        if (0 != strlen(ssid) && WIFI_DISCONNECTED ==  stStatusInfo.connectionStatus) {
            SocSubWifiDisconnect();
            usleep(200 * 1000);
            SocSubWifiConnect(ssid, pwd, WIFI_ENCRYPT_WPA_WPA2);
        }
#else
        if (WIFI_DISCONNECTED ==  stStatusInfo.connectionStatus) {
            SocSubWifiDisconnect();
            usleep(200 * 1000);
            SocSubWifiConnect(ssid, pwd, WIFI_ENCRYPT_WPA_WPA2);
        }
#endif
    }
#endif

     while (1)
     {
         if (ctx->enConfigStatus > WIFI_CONFIG_NONE)
         {
             if (ctx->enConfigStatus == WIFI_CONFIG_SOUNDWAVE_START) //声波接收开始 红灯闪烁
             {
                 LedSet(LED_TYPE_RED, LED_STATE_BLINK, LED_LEVEL_LOW);
             }
             else if (ctx->enConfigStatus == WIFI_CONFIG_CONNECT_START) //WiFi连接开始 红灯快闪
             {
                 LedSet(LED_TYPE_RED, LED_STATE_FAST_BLINK, LED_LEVEL_LOW);
                 /* 统计连接时长,超过指定时长则恢复配置标识,保证指示灯正确显示 */
                 if (ctx->enConnnectStatus == WIFI_DISCONNECTED) {
                     if (connect_count_num++ >= 100) { //100 * 100ms = 10s
                         ctx->enConfigStatus = WIFI_CONFIG_CONNECT_FAILED;
                         connect_count_num = 0;
                     }
                 } else if (ctx->enConnnectStatus == WIFI_CONNECTED) {
                     connect_count_num = 0;
                     ctx->enConfigStatus = WIFI_CONFIG_CONNECT_SUCCESS;
#ifndef MINI_APP
                    #ifdef ZDK_PROTOCOL
                     RealTimeServerClose();
                    #endif /* ZDK_PROTOCOL */
#endif /* MINI_APP */
 
                     /* add alive time to resolve binding failure problem */
                     PowerSetSocSleepTime(AV_TRUE, 30);
 
                     LOGI(">>>>>>>>>>>> success to connect wifi <<<<<<<<<<<<\n");
                     while (AudioGetOpsHandle()->play_file_start(AUDIO_LINK_SUCCESS, AUDIO_TYPE_MP3, 0) < 0) {
                         usleep(100 * 1000);
                     }        

#if 0
                    int ret = 0;
                    int retryCnt = 0;

                    HI_HAL_SYSLINK_Deinit();
retry_init:
                    ret = HI_HAL_SYSLINK_Init();
                    if (ret != 0) {
                        if (++retryCnt >= 5) {
                            SystemReboot("HI_HAL_SYSLINK_Init failed\n");
                        }
                        usleep(500 * 1000);
                        goto retry_init;
                    }
#endif
                    sleep(1);
#ifndef MINI_APP                    
					#ifdef ZDK_PROTOCOL
                     RealTimeServerReStart();
					#endif
#endif /* MINI_APP */
		#ifdef YD_PROTOCOL
                     pthread_t MCGetServerStatusPid;
                     int err = pthread_create(&MCGetServerStatusPid, NULL, &_MCGetRegisterStatus, NULL);
                     if (err != 0) {
                         LOGE("pthread_create MCGetServerStatus failed!\n");
                         return -1;
                     }
		#endif
                 }
             }
         }
         else 
         {
             if (ctx->enConnnectStatus == WIFI_CONNECTED)
             {
                 LedSet(LED_TYPE_BLUE, LED_STATE_ON, LED_LEVEL_LOW);
             }
             else if (ctx->enConnnectStatus == WIFI_DISCONNECTED)
             {       
                 LedSet(LED_TYPE_RED, LED_STATE_ON, LED_LEVEL_LOW);
             }
         }
         usleep(100*1000);
#ifdef YD_PROTOCOL 
	 if (!strlen(mac))
	 {
		GetMmacAddress("wlan0", mac);
		if (strlen(mac))
		{
			GetMmacAddress("wlan0", mac_bak);
			if (strcmp(mac, mac_bak) == 0)
			{
				DOTGetMacAddress(mac);
			}
			else
			{
				memset(mac, 0, 32);
			}
		}
	 }
#endif
     }
     pthread_exit(0);
 }

int hi3861L_set_disconnect(void)
{ 
    SocSubWifiDisconnect();
    return 0;
}


 int hi3861L_set_connect(char *ssid, char *pwd, WIFI_ENCRYPT_TYPE_E enEncryptType)
 {
     int ret = 0;
     char ssidStr[32] = "";
     char pwdStr[64] = "";
     char encryptStr[32] = "";
     char bHex = 0;
     hi3861_context_s *ctx = _hi3861_GetCtx();

     ctx->bConnecting = 1;
     
     _wifi_ssid_conver(ssid, &bHex);
     
     snprintf(ssidStr, sizeof(ssidStr), "%s", ssid);
     snprintf(pwdStr, sizeof(pwdStr), "%s", pwd);
 
     switch (enEncryptType)
     {
         case WIFI_ENCRYPT_OPEN:
             snprintf(encryptStr, sizeof(encryptStr), "%s", "open");
             break;
         case WIFI_ENCRYPT_WPA:
             snprintf(encryptStr, sizeof(encryptStr), "%s", "wpa");
             break;
         case WIFI_ENCRYPT_WPA2:
             snprintf(encryptStr, sizeof(encryptStr), "%s", "wpa2");
             break;
         case WIFI_ENCRYPT_WEP:
             snprintf(encryptStr, sizeof(encryptStr), "%s", "wep");
             break;
         case WIFI_ENCRYPT_WPA_WPA2:
             snprintf(encryptStr, sizeof(encryptStr), "%s", "wpa+wpa2");
             break;
     }
 
     LOGI("ssid: %s pwd: %s encrypt: %s\n", ssidStr, pwdStr, encryptStr);
 
     hi3861L_set_disconnect();
     usleep(100*1000); 
     
     int timeout = 0;
     int reconnectCnt = 0;
     
 retry_connect:
     timeout = 600; //timeout wait 30s
     ctx->enConfigStatus = WIFI_CONFIG_CONNECT_START; //notify red led fast blink
     
     PowerSetSocSleepTime(AV_TRUE, 35);
     
     LOGI(">>>>>>>>>>>> start connect wifi <<<<<<<<<<<<\n");
     ret = SocSubWifiConnect(ssidStr, pwdStr, enEncryptType);
     if(0 != ret) {
         LOGE("fail to send wpa connect command\n");
         while (AudioGetOpsHandle()->play_file_start(AUDIO_LINK_FAIL, AUDIO_TYPE_MP3, 0) < 0) {
             usleep(100 * 1000);
         }
         goto over_return;
     }
 
     while (timeout--)
     {
         if (ctx->enConfigStatus == WIFI_CONFIG_CONNECT_FAILED) 
         {
             if (reconnectCnt < 1) { //重连两次,每次10s
                 LOGW("\n\n >>>>>>>>>>>>>>>> reconnect wifi \n\n");
                 reconnectCnt++;
                 goto retry_connect;
             } else {
                 AudioGetOpsHandle()->play_file_start(AUDIO_LINK_FAIL, AUDIO_TYPE_MP3, 0);
                 break;
             }
             reconnectCnt++;
         } 
         else if (ctx->enConfigStatus == WIFI_CONFIG_CONNECT_SUCCESS) 
         {
             _wifi_set_config(ssidStr, pwdStr, encryptStr);        
             break;
         }

		 #ifdef YD_PROTOCOL
		 if (DOTGetWifiConfigRun())
		 	break;
		 #endif
         usleep(50 * 1000);
     }
     
 over_return:
     ctx->bConnecting = 0;
     ctx->enConfigStatus = WIFI_CONFIG_NONE;
 
     return 0;
 }
 
static int hi3861l_wifi_config_run()
{
    if (UpgradeCheckIsRun()) {
        LOGW("upgrade is running!\n");
        return -1;
    }

    int ret = 0;
    hi3861_context_s *ctx = _hi3861_GetCtx();

    LOGI("wifi config run ......\n");
    ctx->enConfigStatus = WIFI_CONFIG_SOUNDWAVE_START; //notify red led blink
 
#ifdef YD_PROTOCOL
    #ifdef QRCODE_ENABLE
	DOTSetWifiConfigRun(1);
	DOTSetConfigFailParam(1);
	if (WifiCheckIsConnected()) {
		hi3861L_set_disconnect();
    }     
    while (AudioGetOpsHandle()->play_file_start(AUDIO_START_CON, AUDIO_TYPE_MP3, 0) < 0)
    {
		usleep(100 * 1000);
    }	
	
    PowerSetSocSleepTime(AV_TRUE, 60);
	QrcodeScanStart();	

	usleep(500 * 1000);
	DOTStartBind(4);
	
    #endif /* QRCODE_ENABLE */
#else
    static char bConfigRun = 0;
    char ssid[32] = "";
    char password[64] = "";
    WIFI_ENCRYPT_TYPE_E enEncryptType = WIFI_ENCRYPT_NULL;

    if (bConfigRun) {
        LOGW("wifi already config...\n");
        return 0;
    }
    bConfigRun = 1;
    PowerSetWakeLock("WIFI");

    if (WifiCheckIsConnected()) {
        hi3861L_set_disconnect();
    }
    
    while (AudioGetOpsHandle()->play_file_start(AUDIO_START_CON, AUDIO_TYPE_MP3, 0) < 0) {
        usleep(50 * 1000);
    } 
#ifndef MINI_APP
    #ifdef ZDK_PROTOCOL
    RealTimeServerClose();
    #endif /* ZDK_PROTOCOL */
#endif /* MINI_APP */
 


#ifndef MINI_APP

#ifdef SOUND_WAVE
    ret = SoundWaveWifiProcess(ssid, password);
    if (ret < 0) {
        LOGE("SoundWaveWifiProcess failed\n");
        #ifdef ZDK_PROTOCOL
        RealTimeServerReStart();
        #endif
        goto over_return;
    }
#endif /* SOUND_WAVE */

    #ifdef ZDK_PROTOCOL
    RealTimeServerClose();
    #endif /* ZDK_PROTOCOL */
    
#endif /* MINI_APP */

    if (strlen(password) == 0) {
        enEncryptType = WIFI_ENCRYPT_OPEN;
    } else {
        enEncryptType = WIFI_ENCRYPT_WPA_WPA2;
    }

    hi3861L_set_connect(ssid, password, enEncryptType);
     
 over_return:
    ctx->enConfigStatus = WIFI_CONFIG_NONE;
    PowerSetWakeUnLock("WIFI");
    bConfigRun = 0;
#endif /* YD_PROTOCOL */
 
    return ret;
}

static void *tskNetKeyWakeupProc(void*args)
{
    SET_THREAD_NAME("tskNetKeyWakeupProc");
    pthread_detach(pthread_self());

    SYSTEM_WAKEUP_TYPE_E enSysWakeupType = SYS_WAKEUP_TYPE_BUFF;

    SocSubGetWakeUpType(&enSysWakeupType);
    if (SYS_WAKEUP_TYPE_KEY_NETCFG == enSysWakeupType) {
        hi3861l_wifi_config_run();
    }

    pthread_exit(0);
}

int hi3861L_get_link_status()
{
	WIFI_STATUS_INFO_S stStatusInfo;
	memset(&stStatusInfo, 0, sizeof(stStatusInfo));
	hi3861L_get_status(&stStatusInfo);
	if(WIFI_CONNECTED == stStatusInfo.connectionStatus || WIFI_CONNECTED_WITH_INTERNET == stStatusInfo.connectionStatus ){
		return 1;
	}

    return 0;
}

int hi3861L_get_status(WIFI_STATUS_INFO_S *pstStatusInfo)
{
    AV_RETURN_IF_PTR_NULL(pstStatusInfo, AV_FAILURE);

#if 0
    hi3861_context_s *ctx = _hi3861_GetCtx();
    if (NetPing("www.baidu.com", 1, 100)) {
        pstStatusInfo->connectionStatus = WIFI_CONNECTED;
        ctx->enConnnectStatus = WIFI_CONNECTED;
    } else {
        pstStatusInfo->connectionStatus = WIFI_DISCONNECTED;
        ctx->enConnnectStatus = WIFI_DISCONNECTED;
    }
#else
    int ret = 0;
    hi3861_context_s *ctx = _hi3861_GetCtx();

    if (ctx->bConnecting) {
        pstStatusInfo->connectionStatus = WIFI_DISCONNECTED;
        return AV_SUCCESS;
    }
    
    ret = SocSubWifiGetStatus(pstStatusInfo);
    if (ret != AV_SUCCESS) {
          usleep(100 * 1000);
    }
    AV_RETURN_WITH_INFO_IF_EXPR_FALSE(ret == 0 , AV_FAILURE, "SocSubWifiGetStatus");

    if (WIFI_CONNECTED == pstStatusInfo->connectionStatus) {        
        ctx->enConnnectStatus = WIFI_CONNECTED;
    } else {
        ctx->enConnnectStatus = WIFI_DISCONNECTED;
    }
#endif

    return AV_SUCCESS;
}


static void print_hex_buf(char *key, unsigned char *buf, int len)
{
	int i = 0;

	printf("%s: ", key);
	
	for (i = 0; i < len; i++)
	{
		printf("0x%x ", buf[i]);
	}

	printf("\n");
}

int hi3861L_get_sleep_config(WIFI_SLEEP_ATTR_S *pstSleepAttr)
{
    char uuid[32] = "";
    int cnt = 0;
    
#if 0
    /* debug */
    snprintf(pstSleepAttr->server[cnt].ip, sizeof(pstSleepAttr->server[cnt].ip),
                "%s", "192.168.0.23");
    pstSleepAttr->server[cnt].port = 9999;
    cnt++;
#endif
    
#ifdef ZDK_PROTOCOL
    char ip[64] = {0};
    DevGetUuid(uuid);
    snprintf(pstSleepAttr->heartBeatData, sizeof(pstSleepAttr->heartBeatData), 
                "{\"command\":\"300100\", \"client_id\":\"%s\"}", uuid);
    pstSleepAttr->heartBeatLen = strlen(pstSleepAttr->heartBeatData);
    strncpy(pstSleepAttr->wakeupData, "ZDKALIVE", sizeof(pstSleepAttr->wakeupData));
    NetLiteosGetAddrInfo("lph.worthcloud.net", ip);
    snprintf(pstSleepAttr->server[cnt].ip, sizeof(pstSleepAttr->server[cnt].ip),
            "%s", ip);   
//    snprintf(pstSleepAttr->server[cnt].ip, sizeof(pstSleepAttr->server[cnt].ip),
//                "%s", "106.75.148.61");

    pstSleepAttr->server[cnt].port = 9508;
    cnt++;
    
    pstSleepAttr->serverNum = cnt;
    pstSleepAttr->wakeupLen = strlen(pstSleepAttr->wakeupData);
    pstSleepAttr->interval = 60;
#elif YD_PROTOCOL
	DoT_KeepLiveInfo_st liveinfo;
	int i = 0;
	
	memset(&liveinfo, 0, sizeof(DoT_KeepLiveInfo_st));
	if (0 != DoT_GetKeepLiveInfo(&liveinfo)) {
		LOGE("DoT_GetKeepLiveInfo failed\n");
		return -1;
	}
	
	printf("\n\n\n\nWifiGetSleepConfig\n\n\n");
	printf("liveinfo.heartbeat_pkt = 0x%x\n", liveinfo.heartbeat_pkt[0]);
	printf("liveinfo.heartbeat_pkt_len = %d\n", liveinfo.heartbeat_pkt_len);
	printf("liveinfo.wakeup_pkt = 0x%x\n", liveinfo.wakeup_pkt[0]);
	printf("liveinfo.wakeup_pkt_len = %d\n", liveinfo.wakeup_pkt_len);
	printf("liveinfo.server_count = %d\n", liveinfo.server_count);
	printf("liveinfo.heartbeat_interval = %d\n", liveinfo.heartbeat_interval);

	print_hex_buf("heartbeat_pkt", liveinfo.heartbeat_pkt, liveinfo.heartbeat_pkt_len);
	memcpy(pstSleepAttr->heartBeatData, liveinfo.heartbeat_pkt, liveinfo.heartbeat_pkt_len);
    pstSleepAttr->heartBeatLen = liveinfo.heartbeat_pkt_len;
	print_hex_buf("heartBeatData", pstSleepAttr->heartBeatData, liveinfo.heartbeat_pkt_len);
	
	print_hex_buf("wakeup_pkt", liveinfo.wakeup_pkt, liveinfo.wakeup_pkt_len);
	memcpy(pstSleepAttr->wakeupData, liveinfo.wakeup_pkt, liveinfo.wakeup_pkt_len);
	pstSleepAttr->wakeupLen = liveinfo.wakeup_pkt_len;
	print_hex_buf("wakeupData", pstSleepAttr->wakeupData, liveinfo.wakeup_pkt_len);


	pstSleepAttr->serverNum = cnt;
	pstSleepAttr->serverNum = liveinfo.server_count + cnt;
	for (i = cnt; i < pstSleepAttr->serverNum; i++)
	{
		strcpy(pstSleepAttr->server[i].ip, liveinfo.server_address[i-cnt].server_ip);
		pstSleepAttr->server[i].port = liveinfo.server_address[i-cnt].server_port;
		printf("pstSleepAttr->server[%d].ip = %s\n",i,pstSleepAttr->server[i].ip);
		printf("pstSleepAttr->server[%d].port = %d\n",i,pstSleepAttr->server[i].port);
	}
    pstSleepAttr->interval = liveinfo.heartbeat_interval;
#elif TELECOM

#endif
    return 0;
}

int hi3861L_set_sleep_mode(void)
{
    LOGI("test\n");

    int ret = 0;
    WIFI_SLEEP_ATTR_S stSleepAttr;

    //获取WiFi休眠配置
    memset(&stSleepAttr, 0, sizeof(stSleepAttr));
    ret = hi3861L_get_sleep_config(&stSleepAttr); 
    if (ret < 0) {
      LOGE("hi1131s_get_sleep_config failed\n");
      return -1;
    }

    int i = 0;
    HI_SYSLINK_WIFI_KEEPALIEVE_S stKeepAlive = { 0 };

    stKeepAlive.bEnable = 1;
    stKeepAlive.interval = (AV_U16)stSleepAttr.interval;
	memcpy(stKeepAlive.wakeupData, stSleepAttr.wakeupData, stSleepAttr.wakeupLen);
    stKeepAlive.wakeupLen = (AV_U16)stSleepAttr.wakeupLen;
	memcpy(stKeepAlive.keepAliveData, stSleepAttr.heartBeatData, stSleepAttr.heartBeatLen);
    stKeepAlive.keepAliveLen = (AV_U16)stSleepAttr.heartBeatLen;
    stKeepAlive.serverNum = (AV_U8)stSleepAttr.serverNum;
    for (i = 0; i < stKeepAlive.serverNum; i++) 
    {
        stKeepAlive.server[i].addr = inet_addr(stSleepAttr.server[i].ip);
        stKeepAlive.server[i].port = (AV_U16)stSleepAttr.server[i].port;
    }
    stKeepAlive.serverThreshold = 1;

#if 0
    if (UpgradeCheckIsRun()) {
      LOGW("upgrade is running, pause wifi sleep\n");
      return -2;
    }
#endif

    wifisoc_set_keepalive(stKeepAlive);

    return 0;
}

 int hi3861L_init(void)
 {
    int ret = 0;
    pthread_t netKeyWakeupProcPid;
    hi3861_context_s *ctx = _hi3861_GetCtx();

    if (ctx->bInit) {
        LOGW("hi3861L_init already init\n");
        return 0;
    }
    
    ret = pthread_create(&ctx->wifiProcPid, NULL, (void *)tskHi3861WifiProc, NULL);
    if (ret != 0) {
        LOGE("pthread_create tskHi3861WifiProc failed!\n");
        return -1;
    }

    ret = pthread_create(&netKeyWakeupProcPid, NULL, (void *)tskNetKeyWakeupProc, NULL);
    if (ret != 0) {
        LOGE("pthread_create tskNetKeyWakeupProc failed!\n");
        return -1;
    }

    KeyEventRegister(KEY_TYPE_CONFIG, KEY_STATE_PRESSED, hi3861l_wifi_config_run);
    HI_HAL_SYSLINK_Register(_onRecvWifiEvent);

    ctx->bInit = 1;
    
    return 0;
 }

 int hi3861L_deinit(void)
 {
    hi3861_context_s *ctx = _hi3861_GetCtx();

    if (ctx->bInit) {
        KeyEventUnRegister(KEY_TYPE_CONFIG, KEY_STATE_PRESSED, hi3861l_wifi_config_run);
        pthread_cancel(ctx->wifiProcPid);
    }
    
    return 0;
 }

